import 'dart:async';
import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../models/task_model.dart';
import '../../utils/event_bus.dart';
import '../../utils/http_client.dart';
import '../../utils/logger.dart';
import 'task_detail_screen.dart';

class OngoingTasksScreen extends StatefulWidget {
  const OngoingTasksScreen({super.key});

  @override
  State<OngoingTasksScreen> createState() => _OngoingTasksScreenState();
}

class _OngoingTasksScreenState extends State<OngoingTasksScreen> {
  final List<TaskModel> _tasks = [];
  final ScrollController _scrollController = ScrollController();
  bool _isLoading = false;
  bool _hasMore = true;
  int _currentPage = 1;
  static const int _pageSize = 4;
  StreamSubscription? _subscription;

  @override
  void initState() {
    super.initState();
    _loadTasks().then((_) => print('列表${_tasks}'));
    _scrollController.addListener(_onScroll);
    _subscription = eventBus.onTaskStatusChanged.listen((_) {
      print("主页收到");
      _refresh();
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      if (!_isLoading && _hasMore) {
        _loadTasks();
      }
    }
  }

  Future<void> _loadTasks() async {
    if (_isLoading) return;

    setState(() {
      _isLoading = true;
    });

    try {
      final prefs = await SharedPreferences.getInstance();
      final userId = prefs.getString('savedJobNumber');

      final response = await HttpClient.dio.post(
        '/follower/getNewTasking',
        data: {
          'userid': userId,
          'date': DateTime.now().toString().split(' ')[0], // 当前日期
          'page': _currentPage,
          'totle': _pageSize,
        },
      );
      if (response.data['code'] == 0) {
        final List<dynamic> tasksJson = response.data['data']['tasking'] ?? [];
        final List<TaskModel> newTasks =
            tasksJson.map((json) => TaskModel.fromJson(json)).toList();

        setState(() {
          _tasks.addAll(newTasks);
          _currentPage++;
          _hasMore = newTasks.isNotEmpty && newTasks.length >= _pageSize;
          _isLoading = false;
        });
      } else {
        setState(() {
          _hasMore = false;
          _isLoading = false;
        });
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(response.data['msg'] ?? '加载失败')),
          );
        }
      }
    } catch (e) {
      Logger.e('Load tasks error', e);
      setState(() {
        _hasMore = false;
        _isLoading = false;
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('网络错误，请稍后重试')),
        );
      }
    }
  }

  Future<void> _refresh() async {
    if (mounted) {
      setState(() {
        _tasks.clear();
        _currentPage = 1;
        _hasMore = true;
      });
      await _loadTasks();
    }
  }

  Future<void> _showMergeDialog(TaskModel task) async {
    // 获取可合并的任务列表
    final response = await HttpClient.dio.post(
      '/follower/findMergeOrder',
      data: {
        'waybillNumber': task.waybillNumber,
      },
    );
    print(response.data);
    if(response.data['code']!=0){
      if(mounted){
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(response.data['msg'] ?? '加载失败')),
        );
        return;
      }
    }
    List<TaskModel> tasks = [TaskModel.fromJson(response.data['data'])];

    if (mounted) {
      final selectedTask = await showDialog<TaskModel>(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('选择要合并的任务'),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: tasks.map(
                    (task) => Card(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                        side: const BorderSide(color: Colors.orange),
                      ),
                      child: ListTile(
                        title: Text(task.carCode),
                        subtitle: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text('车牌: ${task.carCode}'),
                            Text('司机: ${task.followerName}'),
                            Text('日期: ${task.createTime}'),
                            Text('总店数: ${task.storeCount}'),
                          ],
                        ),
                        onTap: () => Navigator.pop(context, task),
                      ),
                    )
                  )
                  .toList(),
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
          ],
        ),
      );
      print("object");
      if (selectedTask != null) {
        print("object");
        await _mergeTask(task, selectedTask);
      }
    }
  }

  Future<void> _mergeTask(TaskModel task1, TaskModel task2) async {
    try {
      final response = await HttpClient.dio.post(
        '/follower/mergeOrder',
        data: {
          'waybillNumber1': task1.waybillNumber,
          'waybillNumber2': task2.waybillNumber, // 当前日期
        },
      );
      print(response.data);
      if (response.data['code'] == 0) {
        // final List<dynamic> tasksJson = response.data['data']['tasking'] ?? [];
        // final List<TaskModel> newTasks =
        //     tasksJson.map((json) => TaskModel.fromJson(json)).toList();

        // setState(() {
        //   // _tasks.addAll(newTasks);
        //   _currentPage++;
        //   // _hasMore = newTasks.isNotEmpty && newTasks.length >= _pageSize;
        //   _isLoading = false;
        // });
        await _refresh();
      } else {
        setState(() {
          _hasMore = false;
          _isLoading = false;
        });
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(response.data['msg'] ?? '加载失败')),
          );
        }
      }
    } catch (e) {
      Logger.e('Load tasks error', e);
      setState(() {
        _hasMore = false;
        _isLoading = false;
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('网络错误，请稍后重试')),
        );
      }
    }
  }

  // 添加一个方法来检查任务是否可以合并
  bool _canMerge(TaskModel task1, TaskModel task2) {
    // print('${task1.loadingNumber}#${task1.createTime.toString().split(' ')[0]}===${task2.loadingNumber}#${task2.createTime.toString().split(' ')[0]}');
    return task1.carCode == task2.carCode &&
        task1.driverNumber == task2.driverNumber &&
        task1.centerCode != task2.centerCode &&
        task1.createTime.toString().split(' ')[0] == task2.createTime.toString().split(' ')[0];
  }

  // 添加一个方法来获取可合并的任务
  TaskModel? _getMergableTask(TaskModel task) {
    for (var otherTask in _tasks) {
      if (_canMerge(task, otherTask)) {
        return otherTask;
      }
    }
    return null;
  }

  // 添加一个方法来过滤已合并的任务
  List<TaskModel> _filterMergedTasks(List<TaskModel> tasks) {
    final Set<String> mergedTaskIds = {};  // 存储已合并的任务ID
    final List<TaskModel> filteredTasks = [];

    for (var task in tasks) {
      // 如果任务已被合并且不是主任务，跳过
      if (task.mergeState != ""&&task.centerCode!=9902) {
        mergedTaskIds.add(task.waybillNumber);
        continue;
      }

      // 如果任务是主任务或未合并的任务，添加到列表
      filteredTasks.add(task);
    }

    return filteredTasks;
  }

  @override
  Widget build(BuildContext context) {
    // 过滤已合并的任务
    final filteredTasks = _filterMergedTasks(_tasks);
    return Scaffold(
      appBar: AppBar(
        title: const Text('进行中的任务'),
      ),
      body:_isLoading && filteredTasks.isEmpty
          ? const Center(child: CircularProgressIndicator())
          : RefreshIndicator(
        onRefresh: _refresh,
        child: ListView.builder(
          controller: _scrollController,
          padding: const EdgeInsets.all(16),
          itemCount: filteredTasks.length + 1,
          itemBuilder: (context, index) {
            if (index == filteredTasks.length) {
              return _buildLoadingIndicator();
            }

            final task = filteredTasks[index];
            // return Card(
            //   margin: const EdgeInsets.only(bottom: 16),
            //   child: InkWell(
            //     onTap: () async {
            //       await Navigator.push(
            //         context,
            //         MaterialPageRoute(
            //           builder: (context){
            //             return TaskDetailScreen(
            //               taskModel: task,
            //             );
            //           }
            //         ),
            //       );
            //       _refresh();
            //     },
            //     child: Padding(
            //       padding: const EdgeInsets.all(16),
            //       child: Column(
            //         crossAxisAlignment: CrossAxisAlignment.start,
            //         children: [
            //           Row(
            //             mainAxisAlignment: MainAxisAlignment.spaceBetween,
            //             children: [
            //               Text(
            //                 task.carCode,
            //                 style: const TextStyle(
            //                   fontSize: 16,
            //                   fontWeight: FontWeight.bold,
            //                 ),
            //               ),
            //               _buildStatusChip(task.status),
            //             ],
            //           ),
            //           const SizedBox(height: 16), // 替换 Divider，避免布局冲突
            //           Row(
            //             crossAxisAlignment: CrossAxisAlignment.start, // 添加对齐方式
            //             children: [
            //               Expanded(
            //                 child: Column(
            //                   crossAxisAlignment: CrossAxisAlignment.start,
            //                   children: [
            //                     _buildInfoRow('司机', task.driverName),
            //                     const SizedBox(height: 8),
            //                     _buildInfoRow('查询人', task.followerName),
            //                     const SizedBox(height: 8),
            //                     _buildInfoRow('单据来源',
            //                         task.centerCode == 9900
            //                             ? '常温'
            //                             : task.centerCode == 9901
            //                             ? '冷藏'
            //                             : '冷冻'),
            //                     const SizedBox(height: 8),
            //                     _buildInfoRow('创建时间', task.createTime),
            //                   ],
            //                 ),
            //               ),
            //               IconButton(
            //                 icon: const Icon(Icons.merge_type),
            //                 onPressed: () => _mergeTask(task),
            //                 tooltip: '合并任务',
            //               ),
            //             ],
            //           ),
            //         ],
            //       ),
            //     ),
            //   ),
            final mergableTask = _getMergableTask(task);

            return Column(
              children: [
                if (mergableTask != null &&
                    index > 0 &&
                    _getMergableTask(_tasks[index - 1]) != task &&
                    task.mergeState.isEmpty)
                  Container(
                    margin: const EdgeInsets.symmetric(horizontal: 16),
                    height: 24,
                    child: const Row(
                      children: [
                        SizedBox(
                          height: 24,
                          child: VerticalDivider(
                            color: Colors.orange,
                            thickness: 2,
                          ),
                        ),
                        Icon(Icons.merge_type, color: Colors.orange, size: 16),
                        Text(
                          '可合并任务',
                          style: TextStyle(
                            color: Colors.orange,
                            fontSize: 12,
                          ),
                        ),
                      ],
                    ),
                  ),
                Card(
                  margin: const EdgeInsets.symmetric(
                    horizontal: 16,
                    vertical: 8,
                  ),
                  // 如果有可合并的任务，添加橙色边框
                  shape: mergableTask != null && task.mergeState.isEmpty
                      ? RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                          side: const BorderSide(color: Colors.orange),
                        )
                      : task.mergeState.isNotEmpty?RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                      side: const BorderSide(color: Colors.orange)):null,
                  child: ListTile(
                    title: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(task.carCode),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            if (mergableTask != null && task.mergeState.isEmpty)
                              IconButton(
                                icon: const Icon(
                                  Icons.merge_type,
                                  color: Colors.orange,
                                ),
                                onPressed: () => _showMergeDialog(task),
                                tooltip: '合并任务',
                              ),
                            IconButton(
                              icon: const Icon(Icons.arrow_forward_ios),
                              onPressed: () {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) =>
                                        TaskDetailScreen(taskModel: task),
                                  ),
                                );
                              },
                            ),
                          ],
                        )
                      ],
                    ),
                    subtitle: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // if(task.mergeState.isNotEmpty&&task.mergeState!='')
                        //   ...[_buildInfoRow('合并状态', "已合并"),
                        //     const SizedBox(height: 8)],
                        _buildInfoRow('司机', task.driverName),
                        const SizedBox(height: 8),
                        _buildInfoRow('查询人', task.followerName),
                        const SizedBox(height: 8),
                        _buildInfoRow(
                            '单据来源',
                            task.centerCode == 9900
                                ? '常温'
                                : task.centerCode == 9901
                                    ? '冷藏'
                                    : '冷冻'),
                        const SizedBox(height: 8),
                        _buildInfoRow('创建时间', task.createTime),
                        const SizedBox(height: 8),
                        _buildInfoRow('单据号', task.loadingNumber),
                        const SizedBox(height: 8),
                        if (mergableTask != null && task.mergeState.isEmpty)
                          Text(
                            '可与任务 #${mergableTask.loadingNumber} 合并',
                            style: const TextStyle(
                              color: Colors.orange,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                      ],
                    ),
                    trailing: null,
                    isThreeLine: true,
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }

  Widget _buildLoadingIndicator() {
    return Container(
      padding: const EdgeInsets.all(16),
      alignment: Alignment.center,
      child:
          _hasMore ? const CircularProgressIndicator() : const Text('没有更多任务了'),
    );
  }

  Widget _buildInfoRow(String label, String value) {
    return Row(
      children: [
        SizedBox(
          width: 80,
          child: Text(
            label,
            style:  TextStyle(
              color: value=="已合并"?Colors.orange:Colors.grey,
              fontSize: 14,
            ),
          ),
        ),
        Expanded(
          child: Text(
            value,
            style:  TextStyle(fontSize: 14,color:value=="已合并"?Colors.orange:Colors.black87 ),
          ),
        ),
      ],
    );
  }

  Widget _buildStatusChip(int status) {
    Color color;
    String msg;
    // 状态 1.未装车2.已装车3.已发车4.已结束5.已回车 6已完成
    switch (status) {
      case 1:
        msg = "未装车";
        color = Colors.blue;
        break;
      case 2:
        msg = "已装车";
        color = Colors.orange;
        break;
      case 3:
        msg = "已发车";
        color = Colors.green;
        break;
      case 4:
        msg = "已结束";
        color = const Color(0xA44E0956);
        break;
      case 5:
        msg = "已回车";
        color = const Color(0x56A44E09);
        break;
      case 6:
        msg = "已完成";
        color = const Color(0x25C07DFF);
        break;
      default:
        msg = "未知";
        color = Colors.grey;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: color),
      ),
      child: Text(
        msg,
        style: TextStyle(
          color: color,
          fontSize: 12,
        ),
      ),
    );
  }
}
